# -*- coding: utf-8 -*-
# @Time    : 2023/4/11 17:00
# @Author  : wkaanig
# @File    : tools
# @Email   : 15670813638@163.com
# @Software: PyCharm
import re
from html import unescape


def backtracking(response_content, value_in, number=-1, reverse=False):
    """
    回溯，可用于金额，经理，工期等
    将正则后的value_in放入response.text中匹配，如果匹配到，则返回，匹配不到，则向右移动一位
    :param response_content: 网页文本
    :param value_in: 需要检测的字符串，传入元组(value_in)
    :param number: 控制传入的元组类型 value_in 的位置
    :param reverse: 无匹配时移动方向，默认向左移动一位，为 True 时向右移动一位
    :return: 匹配成功的字符串
    """
    if isinstance(value_in, (tuple, list)):
        number = -1 if len(value_in) < (number + 1) else number
        value = value_in[number]
    elif isinstance(value_in, str):
        value = value_in
    else:
        raise ValueError("value_in 必须是str类型或者tuple类型")
    if isinstance(response_content, str):
        while value not in response_content:
            if len(value) == 0:
                break
            if reverse:
                value = value[1:]
            else:
                value = value[:-1]
    else:
        raise ValueError("response_content 必须是str类型")
    if isinstance(value_in, tuple):
        temp_list = list(value_in)
        temp_list[number] = value
        value = tuple(temp_list)
    return value


def smart_backtracking(response_content, value_in, number=-1, reverse=False):
    response_content = re.sub(r'\s+', '', unescape(response_content))
    re_pattern = r'</?(?:a|span|font|u)(?:.*?|)>'
    response_content = re.sub(re_pattern, '', response_content)
    return backtracking(response_content, value_in, number, reverse)
